/**
 * 
 */
package edi.android.tmdbBrowser;

import java.util.List;
import java.util.Set;

import net.sf.jtmdb.Movie;
import net.sf.jtmdb.MoviePoster;
import android.content.Context;
import android.graphics.Typeface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.TextView;

/**
 * @author edi
 * 
 */
public class MovieAdapter extends BaseAdapter implements ListAdapter {
	private List<Movie> items;
	private TMDbApp app;
	private Context context;

	/**
	 * @param items
	 *            The movies to show
	 * @param context
	 *            the context for the imageDownloader
	 */
	public MovieAdapter(Context context, List<Movie> items, TMDbApp app) {
		super();
		this.items = items;
		this.context = context;
		this.app = app;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.widget.Adapter#getCount()
	 */
	@Override
	public int getCount() {
		return items.size();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.widget.Adapter#getItem(int)
	 */
	@Override
	public Movie getItem(int position) {
		return items.get(position);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.widget.Adapter#getItemId(int)
	 */
	@Override
	public long getItemId(int position) {
		return items.get(position).getID();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.widget.Adapter#getView(int, android.view.View,
	 * android.view.ViewGroup)
	 */
	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		final Set<MoviePoster> posters;
		if (convertView == null) {
			LayoutInflater layoutInflater = (LayoutInflater) context
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			convertView = layoutInflater.inflate(R.layout.listrow, null);
		}

		final ImageView imageView = (ImageView) convertView
				.findViewById(R.id.listImage);
		final TextView nameView = (TextView) convertView
				.findViewById(R.id.listPrimary);
		final TextView secondaryView = (TextView) convertView
				.findViewById(R.id.listSecondary);

		nameView.setText(items.get(position).getName());

		// fetching secondary information... original name, if present and not
		// the same as name.
		String secondary = app.chooseSecondaryName(items.get(position), true);

		if (secondary.equals("null")) {
			secondaryView.setVisibility(View.GONE);
		} else {
			secondaryView.setText(secondary);
		}

		// check if the movie got an usable poster
		posters = items.get(position).getImages().posters;
		if (posters != null && !posters.isEmpty()) {
			TMDbApp.imageDownloader.download(posters.iterator().next()
					.getSmallestImage().toString(), imageView);
		} else {
			TMDbApp.imageDownloader.download(
					"http://hwcdn.themoviedb.org/images/no-poster-small.png",
					imageView);
		}
		return convertView;
	}
}
